<?php
class X2FlowRecordEmail extends X2FlowAction {

    public $title = 'Email Contact';
    // Uses the assignee\'s email unless specified.';
    public $info = 'Send a template or custom email to this contact\'s email address.';

    public function paramRules(){
        $credOptsDict = Credentials::getCredentialOptions(null, true);
        $credOpts = $credOptsDict['credentials'];
        $selectedOpt = $credOptsDict['selectedOption'];
        foreach($credOpts as $key => $val){
            if($key == $selectedOpt){
                $credOpts = array($key => $val) + $credOpts; // move to beginning of array
                break;
            }
        }
        return array(
            'title' => Yii::t('studio', $this->title),
            'info' => Yii::t('studio', $this->info),
            'options' => array(
                array('name' => 'from', 'label' => Yii::t('studio', 'Send As:'), 'type' => 'dropdown',
                    'options' => $credOpts),
                //array('name'=>'from','name'=>'from','label'=>Yii::t('studio','From:'),'optional'=>1,'type'=>'email'),
                array('name' => 'template', 'label' => Yii::t('studio', 'Template'), 'type' => 'dropdown', 'defaultVal' => '', 'options' => array('' => Yii::t('studio', 'Custom')) + Docs::getEmailTemplates()),
                array('name' => 'subject', 'label' => Yii::t('studio', 'Subject'), 'optional' => 1),
                array('name' => 'cc', 'label' => Yii::t('studio', 'CC:'), 'optional' => 1, 'type' => 'email'),
                array('name' => 'bcc', 'label' => Yii::t('studio', 'BCC:'), 'optional' => 1, 'type' => 'email'),
                array('name' => 'body', 'label' => Yii::t('studio', 'Message'), 'optional' => 1, 'type' => 'richtext'),
            // 'time' => array('dateTime'),
                ));
    }

    public function execute(&$params){
        $eml = new InlineEmail;
        $options = $this->config['options'];

        if(isset($options['cc']['value']))
            $eml->cc = $this->parseOption('cc', $params);
        if(isset($options['bcc']['value']))
            $eml->bcc = $this->parseOption('bcc', $params);

        $contact = $params['model'];
        if($params['model'] instanceof Contacts){
            if(!$contact->hasAttribute('email') || empty($contact->email))
                return array(false, Yii::t('app', "Email could not be sent"));
            $eml->to = $contact->email;
        }elseif($params['model'] instanceof Actions && strcasecmp($params['model']->associationType, 'contacts') == 0){
            $lookup = X2Model::model('Contacts')->findByPk($params['model']->associationId);
            if(isset($lookup)){
                $contact = $lookup;
                if(!$contact->hasAttribute('email') || empty($contact->email))
                    return array(false, Yii::t('app', "Email could not be sent"));
                $eml->to = $contact->email;
            }else{
                return array(false, Yii::t('app', 'No valid Contact found.'));
            }
        }elseif($params['model'] instanceof X2Model){
            $failure=true;
            foreach($this->getFields() as $field){
                if($field->linkType=='Contacts'){
                    $lookup = X2Model::model('Contacts')->findByPk($params['model']->{$field->fieldName});
                    if(isset($lookup)){
                        $failure=false;
                        $contact = $lookup;
                        if(!$contact->hasAttribute('email') || empty($contact->email))
                            return array(false, Yii::t('app', "Email could not be sent"));
                        $eml->to = $contact->email;
                        break;
                    }
                }
            }
            if($failure){
                return array(false, Yii::t('app', 'No valid Contact found.'));
            }
        }else{
            return array(false, Yii::t('app', 'No valid Contact found.'));
        }

        if(empty($options['from']['value'])){
            $profile = CActiveRecord::model('Profile')->findByAttributes(array('username' => $params['model']->assignedTo));
            if($profile === null)
                return array(false, Yii::t('app', "Email could not be sent"));
            $eml->setUserProfile($profile);
        } else{
            //$eml->from = array('address'=>$this->parseOption('from',$params),'name'=>'');
            $eml->credId = $this->parseOption('from', $params);
        }
        $eml->subject = Formatter::replaceVariables($this->parseOption('subject', $params), $contact);
        $eml->targetModel = $contact;

        if(isset($options['body']['value']) && !empty($options['body']['value'])){ // "body" option (deliberately-entered content) takes precedence over template
            $eml->scenario = 'custom';
            $eml->message = InlineEmail::emptyBody(Formatter::replaceVariables($this->parseOption('body', $params), $contact));
            $eml->prepareBody();
            // $eml->insertSignature(array('<br /><br /><span style="font-family:Arial,Helvetica,sans-serif; font-size:0.8em">','</span>'));
        }elseif(!empty($options['template']['value'])){
            $eml->scenario = 'template';
            $eml->template = $this->parseOption('template', $params);
            $eml->prepareBody();
        }
        // die(var_dump($eml->send(false)));
        $result = $eml->send(false);
        if(isset($result['code']) && $result['code'] == 200){
            return array(true, "");
        }else{
            return array(false, Yii::t('app', "Email could not be sent"));
        }
    }

}
